package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.User;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetMealService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("report")
public class ReportController {

    @Reference
    MemberService memberService;

    @Reference
    SetMealService setMealService;

    @Reference
    ReportService reportService;

    @RequestMapping("getMemberReport")
    public Result getMemberReport() {
        Map<String, Object> map = new HashMap<>();
        List<String> months = new ArrayList<>();


        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -12);

        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH, 1);
            Date time = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy.MM").format(time));
        }
        map.put("months", months);


        List<Integer> memberCount = memberService.findMemberCountByMonth(months);
        map.put("memberCount", memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
    }


    @RequestMapping("getSetmealReport")
    public Result getSetmealReport() {

        try {


            Map<String, Object> data = new HashMap<>();

            List<String> setMealNames = new ArrayList<>();
            List<Map<String, Object>> setMealCount = setMealService.findSetMealCount();

            data.put("setMealCount", setMealCount);


            //对setMealNames进行赋值
            for (Map<String, Object> map : setMealCount) {
                String name = (String) map.get("name");
                setMealNames.add(name);
            }

            data.put("setMealNames", setMealNames);

            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);

        }
    }


    @RequestMapping("getBusinessReportData")
    public Result getBusinessReportData() {

        try {
            Map<String, Object> data = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);

        }
    }


    @RequestMapping("exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response, HttpServletRequest request) {

        try {
            Map<String, Object> result = reportService.getBusinessReportData();


            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");

            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");


            String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));


            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);

            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);//日期

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);
            row.getCell(7).setCellValue(totalMember);

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);
            row.getCell(7).setCellValue(thisMonthNewMember);

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);
            row.getCell(7).setCellValue(todayVisitsNumber);

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);
            row.getCell(7).setCellValue(thisWeekVisitsNumber);

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);
            row.getCell(7).setCellValue(thisMonthVisitsNumber);

            int rowNum = 12;
            for (Map map : hotSetmeal) {
                //热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比 }
            }

            ServletOutputStream os = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition","attachment;filename=report.xlsx");
            excel.write(os);
            os.flush();
            os.close();
            excel.close();


            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);

        }
    }

    /**
     * 将用户数据导出到Excel
     *
     * @param response
     * @param request
     */
    @RequestMapping("exportUserReport")
    public void exportUserReport(HttpServletResponse response, HttpServletRequest request) {

        try {
            List<User> list = reportService.exportUserReport();
            String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "user_template.xlsx";
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);

            for (int i = 0; i < list.size(); i++) {
                int rowNum = 2;
                XSSFRow row = sheet.createRow(1 + i);
                User user = list.get(i);
                //序号
                if (user.getId() == null) {
                    row.createCell(0).setCellValue(" ");
                } else {
                    row.createCell(0).setCellValue(user.getId());
                }
                //用户名
                if (user.getUsername() == null) {
                    row.createCell(1).setCellValue("");
                } else {
                    row.createCell(1).setCellValue(user.getUsername());
                }

                //密码
                if (user.getPassword() == null) {
                    row.createCell(2).setCellValue("");
                } else {
                    row.createCell(2).setCellValue(user.getPassword());
                }
                //出生日期
                if (user.getBirthday() == null) {
                    row.createCell(3).setCellValue("0000-00-00 ");
                } else {
                    row.createCell(3).setCellValue(user.getBirthday());
                }

                //电话号码
                if (user.getTelephone() == null) {
                    row.createCell(4).setCellValue("");
                } else {
                    row.createCell(4).setCellValue(user.getTelephone());
                }
            }
            ServletOutputStream os = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=user.xlsx");
            excel.write(os);
            os.flush();
            os.close();
            excel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
